#include <math.h>
#include "cExceptions.h"
#include "cGFXFile4BPP.h"
#include "uint.h"

GFXFile4BPP::GFXFile4BPP()
{
	gfxData = NULL;
}

void GFXFile4BPP::load(u8* data, u16 size)
{
	if(gfxData != NULL)
		delete[] gfxData;
	gfxData = NULL;

	u16 tiles = ceil(size/32.0);
	u8* ptr;
	try
	{
		ptr = new char[tiles*64];
	}
	catch(...)
	{
		throw new OutOfMemoryException();
	}
	u8 a, b;
	u16 tile = 0;
	for (u16 i = 0 ; i < size ; tile++)
    {
		for (u8 y = 0; y < 8; y++)
        {
			a = data[i++];
            b = data[i++];
            for (int x = 7; x >= 0; x--)
				ptr[(tile << 6) | (y << 3) | x ] = (u8)(((a >> x) & 1) | (((b >> x) << 1) & 2));
		}
        for (u8 y = 0; y < 8; y++)
        {
            a = data[i++];
            b = data[i++];
            for (int x = 7; x >= 0; x--)
				ptr[(tile << 6) | (y << 3) | x ] |= (u8)((((a >> x)<<2) & 4) | (((b >> x) <<3) & 8));
        }
    }
	gfxData = ptr;
}

void GFXFile4BPP::load3BPP(u8* data, u16 size)
{
	throw new UnimplementedException();
}
